var express = require('express');
var router = express.Router();
const { pdfyjlModel } = require('../db/pdfyjl')
const multiparty = require('multiparty');
const path = require('path');
const fs = require('fs');

/* 项目信息配置*/
// 获取列表
router.get('/pdfList', async (req, res) => {
    try {
        // 获取分页和搜索参数
        const page = parseInt(req.query.page);
        const pageSize = parseInt(req.query.size);
        const creator = req.query.creator;
        const phone = req.query.phone;
        
        // 构建查询条件
        let query = {};
        if (creator) {
            query.creator = { $regex: creator, $options: 'i' };
        }
        if (phone) {
            query.phone = { $regex: phone, $options: 'i' };
        }
        
        // 计算跳过的文档数量
        const skip = (page - 1) * pageSize;
        
        // 获取总数据条数
        const total = await pdfyjlModel.countDocuments(query);
        
        // 获取分页数据
        const pdflist = await pdfyjlModel.find(query)
            .skip(skip)
            .limit(pageSize)
            // .sort({ createTime: -1 }); // 按创建时间倒序排列
        
        res.send({
            pdflist,
            total,
            currentPage: page,
            pageSize
        });
    } catch (error) {
        console.error('获取列表失败:', error);
        res.status(500).send({
            message: '获取列表失败',
            error: error.message
        });
    }
});

// 文件上传功能
router.post('/upload', (req, res) => {
    // 创建 multiparty 实例
    const form = new multiparty.Form({
        uploadDir: path.join(__dirname, '../public/uploads'), // 文件保存目录
        maxFilesSize: 10 * 1024 * 1024, // 最大文件大小 10MB
    });

    // 确保上传目录存在
    const uploadDir = path.join(__dirname, '../public/uploads');
    if (!fs.existsSync(uploadDir)) {
        fs.mkdirSync(uploadDir, { recursive: true });
    }

    form.parse(req, (err, fields, files) => {
        if (err) {
            console.error('文件上传错误:', err);
            return res.status(500).json({
                success: false,
                message: '文件上传失败',
                error: err.message
            });
        }

        try {
            const uploadedFiles = [];
            
            // 处理上传的文件
            Object.keys(files).forEach(key => {
                const fileArray = files[key];
                fileArray.forEach(file => {
                    const originalName = file.originalFilename;
                    const oldPath = file.path;
                    const fileSize = file.size;
                    
                    // 构建新路径，使用原始文件名
                    const newPath = path.join(path.dirname(oldPath), originalName);
                    
                    // 如果文件已存在，添加时间戳
                    if (fs.existsSync(newPath)) {
                        const timestamp = Date.now();
                        const ext = path.extname(originalName);
                        const nameWithoutExt = path.basename(originalName, ext);
                        const newFileName = `${nameWithoutExt}_${timestamp}${ext}`;
                        const finalPath = path.join(path.dirname(oldPath), newFileName);
                        
                        // 重命名文件
                        fs.renameSync(oldPath, finalPath);
                        
                        uploadedFiles.push({
                            fieldName: key,
                            originalName: originalName,
                            newPath: finalPath,
                            fileSize: fileSize,
                            url: `/uploads/${newFileName}`
                        });
                    } else {
                        // 直接重命名文件
                        fs.renameSync(oldPath, newPath);
                        
                        uploadedFiles.push({
                            fieldName: key,
                            originalName: originalName,
                            newPath: newPath,
                            fileSize: fileSize,
                            url: `/uploads/${originalName}`
                        });
                    }
                });
            });

            console.log('文件上传成功:', uploadedFiles);
            
            res.json({
                success: true,
                message: '文件上传成功',
                files: uploadedFiles
            });
        } catch (error) {
            console.error('处理上传文件时出错:', error);
            res.status(500).json({
                success: false,
                message: '处理文件时出错',
                error: error.message
            });
        }
    });
});

// 新增函件记录
router.post('/add', async (req, res) => {
    try {
        const {
            type,
            phase,
            signFile,
            origFile,
            client,
            phone,
            status,
            creator
        } = req.body;

        // 获取当前最大的ID
        const maxRecord = await pdfyjlModel.findOne().sort({ ID: -1 });
        console.log(maxRecord);
        
        const newId = maxRecord ? parseInt(maxRecord.ID) + 1 : 1;

        // 获取当前时间
        const currentTime = new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });

        // 计算天数（从创建时间到当前时间）
        const calculateDays = (createTime) => {
            const createDate = new Date(createTime);
            const currentDate = new Date();
            const diffTime = Math.abs(currentDate - createDate);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            return diffDays;
        };

        const newRecord = new pdfyjlModel({
            ID: newId.toString(),
            type: type || '',
            phase: phase || '',
            signFile: signFile || '',
            origFile: origFile || '',
            client: client || '',
            phone: phone || '',
            status: status || '待签署',
            statusType: 'blue',
            creator: creator || '',
            createTime: currentTime,
            updateTime: currentTime,
            days: 0 // 初始天数为0
        });

        const savedRecord = await newRecord.save();
        console.log('新增函件记录成功:', savedRecord);

        res.json({
            success: true,
            message: '新增函件记录成功',
            data: savedRecord
        });
    } catch (error) {
        console.error('新增函件记录失败:', error);
        res.status(500).json({
            success: false,
            message: '新增函件记录失败',
            error: error.message
        });
    }
});

// 添加一个更新天数的接口
router.put('/updateDays/:id', async (req, res) => {
    try {
        const id = req.params.id;
        const record = await pdfyjlModel.findById(id);
        
        if (!record) {
            return res.status(404).json({
                success: false,
                message: '记录不存在'
            });
        }

        // 计算天数
        const createDate = new Date(record.createTime);
        const currentDate = new Date();
        const diffTime = Math.abs(currentDate - createDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

        // 更新天数
        record.days = diffDays;
        record.updateTime = currentDate.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
        });

        await record.save();

        res.json({
            success: true,
            message: '天数更新成功',
            data: record
        });
    } catch (error) {
        console.error('更新天数失败:', error);
        res.status(500).json({
            success: false,
            message: '更新天数失败',
            error: error.message
        });
    }
});

// 删除函件记录
router.delete('/deletePdf/:id', async (req, res) => {
    try {
        const id = req.params.id;
        const result = await pdfyjlModel.findByIdAndDelete(id);
        
        if (!result) {
            return res.status(404).json({
                success: false,
                message: '记录不存在'
            });
        }

        // 删除相关文件
        if (result.signFile) {
            const signFilePath = path.join(__dirname, '../public/uploads', path.basename(result.signFile));
            if (fs.existsSync(signFilePath)) {
                fs.unlinkSync(signFilePath);
            }
        }
        if (result.origFile) {
            const origFilePath = path.join(__dirname, '../public/uploads', path.basename(result.origFile));
            if (fs.existsSync(origFilePath)) {
                fs.unlinkSync(origFilePath);
            }
        }

        res.json({
            success: true,
            message: '删除成功'
        });
    } catch (error) {
        console.error('删除失败:', error);
        res.status(500).json({
            success: false,
            message: '删除失败',
            error: error.message
        });
    }
});

module.exports = router;